#include "icon_manager.h"
#include "modern_icons.h"
#include "icon_design_specs.h"
#include <QMainWindow>
#include <QResizeEvent>
#include <QSettings>
#include <QFileDialog>
#include <QMessageBox>
#include <QStyle>
#include <QApplication>

IconManager::IconManager(QMainWindow* mainWindow, QObject* parent)
    : QObject(parent)
    , m_mainWindow(mainWindow)
    , m_modernIcons(nullptr)
    , m_fileToolBar(nullptr)
    , m_importAction(nullptr)
    , m_exportAction(nullptr)
    , m_currentIconSize(IconDesignSpecs::MEDIUM_SIZE)
    , m_isDarkMode(false)
    , m_isInitialized(false)
    , m_themeColor("#007AFF")
    , m_defaultExportMode(ModernIcons::SeparateMode)
{
    // 构造函数中不做复杂的初始化，延迟到initialize()函数
}

IconManager::~IconManager()
{
    saveSettings();
}

void IconManager::initialize()
{
    if (m_isInitialized) {
        return;
    }

    // 创建现代图标系统
    m_modernIcons = new ModernIcons(this);
    m_modernIcons->setExportMode(m_defaultExportMode);
    m_modernIcons->setThemeColor(m_themeColor);
    m_modernIcons->setDarkMode(m_isDarkMode);

    // 创建工具条和动作
    createFileToolBar();
    createActions();
    setupConnections();

    // 加载设置
    loadSettings();

    // 应用初始状态
    updateAllIcons();
    updateActionTooltips();

    m_isInitialized = true;
}

void IconManager::createFileToolBar()
{
    if (!m_mainWindow) {
        return;
    }

    // 创建工具条
    m_fileToolBar = new QToolBar(tr("文件操作"), m_mainWindow);
    m_fileToolBar->setObjectName("fileToolBar");
    m_fileToolBar->setMovable(false);
    m_fileToolBar->setFloatable(false);

    // 设置工具条样式
    updateToolBarStyle();

    // 添加到主窗口
    m_mainWindow->addToolBar(m_fileToolBar);
}

void IconManager::createActions()
{
    if (!m_modernIcons) {
        return;
    }

    // 导入动作
    m_importAction = new QAction(m_modernIcons->createThemedImportIcon(), tr("导入文件"), this);
    m_importAction->setShortcut(QKeySequence("Ctrl+O"));
    m_importAction->setStatusTip(tr("导入图片或PDF文件"));
    m_importAction->setToolTip(tr("导入文件") + "\n" + tr("支持图片和PDF格式"));

    // 导出动作
    m_exportAction = new QAction(m_modernIcons->createThemedExportIcon(m_defaultExportMode),
                                tr("导出PDF"), this);
    m_exportAction->setShortcut(QKeySequence("Ctrl+E"));
    m_exportAction->setStatusTip(m_modernIcons->exportModeDescription(m_defaultExportMode));
    m_exportAction->setToolTip(tr("导出PDF") + "\n" + m_modernIcons->exportModeDescription(m_defaultExportMode) +
                                "\n" + tr("双击切换模式"));

    // 添加到工具条
    if (m_fileToolBar) {
        m_fileToolBar->addAction(m_importAction);
        m_fileToolBar->addSeparator();
        m_fileToolBar->addAction(m_exportAction);
    }
}

void IconManager::setupConnections()
{
    if (!m_modernIcons || !m_importAction || !m_exportAction) {
        return;
    }

    // 动作连接
    connect(m_importAction, &QAction::triggered, this, &IconManager::onImportActionTriggered);
    connect(m_exportAction, &QAction::triggered, this, &IconManager::onExportActionTriggered);

    // 图标系统连接
    connect(m_modernIcons, &ModernIcons::exportModeChanged, this, &IconManager::onExportModeChanged);

    // 窗口大小变化监听
    if (m_mainWindow) {
        // 事件过滤器将在需要时安装
    }

    // 工具条交互增强
    if (m_fileToolBar) {
        // 图标大小变化监听
        connect(m_fileToolBar, &QToolBar::iconSizeChanged, this, &IconManager::onIconSizeChanged);

        // 添加导出模式的简单切换机制
        // 使用快捷键或菜单来切换，而不是双击和右键
        if (m_exportAction) {
            // 添加中键点击切换模式的功能（使用QVariant包装）
            m_exportAction->setData(QVariant(true)); // 标记支持模式切换
        }
    }
}

void IconManager::updateAllIcons()
{
    if (!m_modernIcons || !m_importAction || !m_exportAction) {
        return;
    }

    QColor themeColor = m_modernIcons->getAdaptiveThemeColor();

    // 更新导入图标
    m_importAction->setIcon(m_modernIcons->createImportIcon(themeColor));

    // 更新导出图标
    m_exportAction->setIcon(m_modernIcons->createExportIcon(m_modernIcons->exportMode(), themeColor));
}

void IconManager::updateIconVariants()
{
    // 这里可以添加不同状态的图标变体处理
    // 目前暂时不需要复杂的变体处理
}

void IconManager::updateToolBarStyle()
{
    if (!m_fileToolBar) {
        return;
    }

    QString styleSheet = getModernToolBarStyle(m_isDarkMode);
    m_fileToolBar->setStyleSheet(styleSheet);
}

void IconManager::setExportMode(ModernIcons::ExportMode mode)
{
    if (m_modernIcons) {
        m_modernIcons->setExportMode(mode);
    }
}

ModernIcons::ExportMode IconManager::exportMode() const
{
    return m_modernIcons ? m_modernIcons->exportMode() : ModernIcons::SeparateMode;
}

void IconManager::toggleExportMode()
{
    if (m_modernIcons) {
        m_modernIcons->toggleExportMode();
    }
}

void IconManager::setThemeColor(const QColor& color)
{
    m_themeColor = color;
    if (m_modernIcons) {
        m_modernIcons->setThemeColor(color);
        updateAllIcons();
        emit themeChanged(color);
    }
}

QColor IconManager::themeColor() const
{
    return m_themeColor;
}

void IconManager::setDarkMode(bool dark)
{
    m_isDarkMode = dark;
    if (m_modernIcons) {
        m_modernIcons->setDarkMode(dark);
        updateAllIcons();
        updateToolBarStyle();
    }
}

bool IconManager::isDarkMode() const
{
    return m_isDarkMode;
}

void IconManager::setIconSize(int size)
{
    m_currentIconSize = size;
    if (m_fileToolBar) {
        m_fileToolBar->setIconSize(QSize(size, size));
        applyIconSizes();
    }
}

int IconManager::iconSize() const
{
    return m_currentIconSize;
}

void IconManager::updateIconSizes()
{
    if (!m_fileToolBar) {
        return;
    }

    // 根据窗口大小智能选择图标尺寸
    if (m_mainWindow) {
        QSize windowSize = m_mainWindow->size();
        int adaptiveSize = IconDesignSpecs::MEDIUM_SIZE; // 默认中等尺寸

        if (windowSize.width() < 800) {
            adaptiveSize = IconDesignSpecs::SMALL_SIZE;
        } else if (windowSize.width() < 1200) {
            adaptiveSize = IconDesignSpecs::MEDIUM_SIZE;
        } else if (windowSize.width() < 1600) {
            adaptiveSize = IconDesignSpecs::LARGE_SIZE;
        } else {
            adaptiveSize = IconDesignSpecs::XLARGE_SIZE;
        }

        setIconSize(adaptiveSize);
    }
}

void IconManager::saveSettings()
{
    QSettings settings;
    settings.beginGroup("IconManager");

    settings.setValue("ExportMode", static_cast<int>(m_modernIcons->exportMode()));
    settings.setValue("ThemeColor", m_themeColor);
    settings.setValue("DarkMode", m_isDarkMode);
    settings.setValue("IconSize", m_currentIconSize);

    settings.endGroup();
}

void IconManager::loadSettings()
{
    QSettings settings;
    settings.beginGroup("IconManager");

    m_defaultExportMode = static_cast<ModernIcons::ExportMode>(
        settings.value("ExportMode", static_cast<int>(ModernIcons::SeparateMode)).toInt());

    m_themeColor = settings.value("ThemeColor", QColor("#007AFF")).value<QColor>();
    m_isDarkMode = settings.value("DarkMode", false).toBool();
    m_currentIconSize = settings.value("IconSize", IconDesignSpecs::MEDIUM_SIZE).toInt();

    settings.endGroup();

    // 应用到图标系统
    if (m_modernIcons) {
        m_modernIcons->setExportMode(m_defaultExportMode);
        m_modernIcons->setThemeColor(m_themeColor);
        m_modernIcons->setDarkMode(m_isDarkMode);
    }
}

// 静态样式方法
QString IconManager::getToolBarStyleSheet(bool darkMode)
{
    if (darkMode) {
        return R"(
            QToolBar {
                background: rgba(45, 45, 48, 0.95);
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 12px;
                padding: 10px;
                margin: 8px;
                spacing: 8px;
            }

            QToolButton {
                background: transparent;
                border: none;
                border-radius: 6px;
                padding: 8px;
                margin: 2px;
                color: #ffffff;
            }

            QToolButton:hover {
                background: rgba(0, 122, 255, 0.2);
            }

            QToolButton:pressed {
                background: rgba(0, 122, 255, 0.3);
            }

            QToolBar::separator {
                background: rgba(255, 255, 255, 0.1);
                width: 1px;
                height: 20px;
                margin: 4px;
            }
        )";
    } else {
        return R"(
            QToolBar {
                background: rgba(255, 255, 255, 0.95);
                border: 1px solid rgba(0, 0, 0, 0.1);
                border-radius: 12px;
                padding: 10px;
                margin: 8px;
                spacing: 8px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            QToolButton {
                background: transparent;
                border: none;
                border-radius: 6px;
                padding: 8px;
                margin: 2px;
                color: #333333;
            }

            QToolButton:hover {
                background: rgba(0, 122, 255, 0.1);
                color: #007AFF;
            }

            QToolButton:pressed {
                background: rgba(0, 122, 255, 0.2);
            }

            QToolBar::separator {
                background: rgba(0, 0, 0, 0.1);
                width: 1px;
                height: 20px;
                margin: 4px;
            }
        )";
    }
}

QString IconManager::getModernToolBarStyle(bool darkMode)
{
    QString baseStyle = getToolBarStyleSheet(darkMode);

    QString modernStyle = baseStyle + R"(
        QToolButton {
            transition: background-color 150ms ease;
        }

        QToolButton:hover {
            transform: translateY(-1px);
        }

        QToolButton:pressed {
            transform: translateY(0);
        }
    )";

    return modernStyle;
}

// 私有槽函数实现
void IconManager::onImportActionTriggered()
{
    emit importTriggered();
}

void IconManager::onExportActionTriggered()
{
    emit exportTriggered();
}

void IconManager::onExportIconChanged(const QIcon& icon)
{
    if (m_exportAction) {
        m_exportAction->setIcon(icon);
    }
}

void IconManager::onExportModeChanged(ModernIcons::ExportMode mode)
{
    updateActionTooltips();
    emit exportModeChanged(mode);
}

void IconManager::onWindowResized()
{
    updateIconSizes();
}

void IconManager::onIconSizeChanged(const QSize& size)
{
    Q_UNUSED(size)
    // 可以在这里处理图标大小变化
}

void IconManager::updateActionTooltips()
{
    if (!m_modernIcons || !m_importAction || !m_exportAction) {
        return;
    }

    // 更新导入动作提示
    m_importAction->setToolTip(tr("导入文件") + "\n" + tr("支持图片和PDF格式") + "\nCtrl+O");

    // 更新导出动作提示
    QString exportTooltip = tr("导出PDF") + "\n" +
                           m_modernIcons->exportModeDescription(m_modernIcons->exportMode()) +
                           "\n" + tr("当前模式：") + m_modernIcons->exportModeText(m_modernIcons->exportMode()) +
                           "\nCtrl+E";
    m_exportAction->setToolTip(exportTooltip);
    m_exportAction->setStatusTip(m_modernIcons->exportModeDescription(m_modernIcons->exportMode()));
}

void IconManager::showExportModeMenu(const QPoint& pos)
{
    Q_UNUSED(pos)

    if (!m_modernIcons) {
        return;
    }

    QMenu menu;
    menu.setStyleSheet(getToolBarStyleSheet(m_isDarkMode));

    ModernIcons::ExportMode currentMode = m_modernIcons->exportMode();

    QAction* separateAction = menu.addAction(tr("分别导出模式"));
    QAction* mergedAction = menu.addAction(tr("合并导出模式"));

    separateAction->setCheckable(true);
    mergedAction->setCheckable(true);

    if (currentMode == ModernIcons::SeparateMode) {
        separateAction->setChecked(true);
    } else {
        mergedAction->setChecked(true);
    }

    QAction* selected = menu.exec(QCursor::pos());
    if (selected == separateAction) {
        setExportMode(ModernIcons::SeparateMode);
    } else if (selected == mergedAction) {
        setExportMode(ModernIcons::MergedMode);
    }
}

void IconManager::applyIconSizes()
{
    if (!m_fileToolBar) {
        return;
    }

    // 应用当前图标尺寸
    QSize iconSize(m_currentIconSize, m_currentIconSize);
    m_fileToolBar->setIconSize(iconSize);

    // 调整工具条高度以适应图标
    int toolBarHeight = m_currentIconSize + 20; // 图标高度 + 内边距
    m_fileToolBar->setMinimumHeight(toolBarHeight);
    m_fileToolBar->setMaximumHeight(toolBarHeight);
}

void IconManager::setToolBarVisible(bool visible)
{
    if (m_fileToolBar) {
        m_fileToolBar->setVisible(visible);
    }
}

// 事件过滤器
bool IconManager::eventFilter(QObject* obj, QEvent* event)
{
    if (obj == m_mainWindow && event->type() == QEvent::Resize) {
        QTimer::singleShot(100, this, &IconManager::onWindowResized); // 防抖处理
    }
    return QObject::eventFilter(obj, event);
}

